﻿using System.Windows;
using eLearning.Model;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Net;
using System;
using Newtonsoft.Json;
using System.Text;

namespace eLearning.MahasiswaView
{
    public partial class PerkuliahanDetailPage : PhoneApplicationPage
    {
        private Perkuliahan kuliah;

        public PerkuliahanDetailPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(RssItemPage_Loaded);
        }

        private void RssItemPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.KULIAH))
            {
                kuliah = (Perkuliahan)PhoneApplicationService.Current.State[Config.KULIAH];                
            }

            if (kuliah != null)
            {
                textKuliah.Text = kuliah.DetMatkul.Matkul.ToString();
                textDosen.Text = kuliah.DetMatkul.Creator.Nama;
                textMatkul.Text = kuliah.DetMatkul.Matkul.Nama;
                textTahunAjaran.Text = kuliah.DetMatkul.TahunAjaran;
                textSemester.Text = kuliah.DetMatkul.Matkul.Semester.ToString();
                textSKS.Text = kuliah.DetMatkul.Matkul.SKS.ToString();
            }
        }

        private void JoinToThisPerkuliahan()
        {
            string url = string.Format("{0}&{1}", Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.JOIN_PERKULIAHAN_KEY, Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(kuliah);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(joinKuliah_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void joinKuliah_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Cancelled && e.Error != null)
            {
                return;
            }
            MessageBox.Show("Message : " + e.Result);
        }

        private void buttonJoin_Click(object sender, System.EventArgs e)
        {
            if (MessageBox.Show("Join to perkuliahan " + kuliah.DetMatkul.Matkul.Nama + "?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                JoinToThisPerkuliahan();
            }
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

    }
}